<?php

namespace App\Http\Middleware;

use App\Lib\Jwt;
use App\Models\AccessLogModel;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AfterAccess
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $response = $next($request);
        if( env('ACCESS_LOG_IN_DB', false) ===  true ) {
            $params = $request->post();
            $data = [
                'platform_id'       => $request->header('App-Platform-Id'),
                'method'            => $request->method(),
                'user_id'           => $request->userId,
                'ver'               => $request->header('Client-version'),
                'route'             => $request->getPathInfo(),
                'client_ip'         => $request->ip(),
                'params'            => $params ? json_encode($params) : '',
                'user_agent'        => $request->userAgent(),
                'time'              => round(microtime(true) - START_ACCESS, 3)
            ];


            DB::beginTransaction();
            try {
                AccessLogModel::query()->create($data);
                DB::commit();
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                DB::rollback();
            }
        }

        return $response;
    }

}

